//base64格式文件下载
function dataURLtoBlob(dataurl) {
  var arr = dataurl.split(',');
  var mime = arr[0].match(/:(.*?);/)[1];
  var bstr = atob(arr[1]);
  var n = bstr.length;
  var u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

function downloadFile(url, name = '文件') {
  var a = document.createElement('a');
  a.setAttribute('href', url);
  a.setAttribute('download', name);
  a.setAttribute('target', '_blank');
  let clickEvent = document.createEvent('MouseEvents');
  clickEvent.initEvent('click', true, true);
  a.dispatchEvent(clickEvent);
}

function downloadFileByBase64(base64, name) {
  // ie10以下浏览器
  if (has('ie') && has('ie') < 10) {
    const oWin = window.top.open('about:blank', '_blank');
    oWin.document.charset = 'utf-8';
    oWin.document.write(base64);
    oWin.document.close();
    oWin.document.execCommand('SaveAs', name + '.csv');
    oWin.close();
  }
  // ie10及以上浏览器
  else if (has('ie') === 10 || _isIE11() || _isEdge()) {
    const BOM = '\uFEFF';
    const csvData = new Blob([BOM + base64], { type: 'text/csv' });
    navigator.msSaveBlob(csvData, name + '.csv');
  }
  // 其它浏览器
  else {
    var myBlob = dataURLtoBlob(base64);
    var myUrl = URL.createObjectURL(myBlob);
    downloadFile(myUrl, name);
  }
}

function has(browser) {
  const ua = navigator.userAgent;
  if (browser === 'ie') {
    const isIE = ua.indexOf('compatible') > -1 && ua.indexOf('MSIE') > -1;
    if (isIE) {
      const reIE = new RegExp('MSIE (\\d+\\.\\d+);');
      reIE.test(ua);
      return parseFloat(RegExp['$1']);
    } else {
      return false;
    }
  } else {
    return ua.indexOf(browser) > -1;
  }
}

// 判断是否是ie11浏览器
function _isIE11() {
  let iev = 0;
  const ieold = /MSIE (\d+\.\d+);/.test(navigator.userAgent);
  const trident = !!navigator.userAgent.match(/Trident\/7.0/);
  const rv = navigator.userAgent.indexOf('rv:11.0');

  if (ieold) {
    iev = Number(RegExp.$1);
  }
  if (navigator.appVersion.indexOf('MSIE 10') !== -1) {
    iev = 10;
  }
  if (trident && rv !== -1) {
    iev = 11;
  }

  return iev === 11;
}
// 判断是否是edge浏览器
function _isEdge() {
  return /Edge/.test(navigator.userAgent);
}
export default downloadFileByBase64;
